<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Python," />





  <link rel="alternate" href="/atom.xml" title="Martin's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="在平常的工作中，有时候会有搭建一个服务器做测试的需求，但也不用有其它太多要求。下面介绍几种用Python搭建服务器的方法。">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="用Python搭建Web服务器">
<meta property="og:url" content="http://martint.oschina.io/2016/05/27/用Python搭建Web服务器/index.html">
<meta property="og:site_name" content="Martin&#39;s Blog">
<meta property="og:description" content="在平常的工作中，有时候会有搭建一个服务器做测试的需求，但也不用有其它太多要求。下面介绍几种用Python搭建服务器的方法。">
<meta property="og:updated_time" content="2017-11-06T14:59:05.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="用Python搭建Web服务器">
<meta name="twitter:description" content="在平常的工作中，有时候会有搭建一个服务器做测试的需求，但也不用有其它太多要求。下面介绍几种用Python搭建服务器的方法。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://martint.oschina.io/2016/05/27/用Python搭建Web服务器/"/>





  <title>用Python搭建Web服务器 | Martin's Blog</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Martin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">每天进步一点</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://martint.oschina.io/2016/05/27/用Python搭建Web服务器/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Martin Tang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Martin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">用Python搭建Web服务器</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-05-27T17:36:21+08:00">
                2016-05-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/技术笔记/" itemprop="url" rel="index">
                    <span itemprop="name">技术笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2016/05/27/用Python搭建Web服务器/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/05/27/用Python搭建Web服务器/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在平常的工作中，有时候会有搭建一个服务器做测试的需求，但也不用有其它太多要求。下面介绍几种用Python搭建服务器的方法。<br><a id="more"></a></p>
<h2 id="最简单的Web服务器搭建"><a href="#最简单的Web服务器搭建" class="headerlink" title="最简单的Web服务器搭建"></a>最简单的Web服务器搭建</h2><p>python自带的web模块就包含BaseHTTPServer，SimpleHTTPServer和CGIHTTPServer这三种。所以使用python自带的包就能快速搭建起python服务器。</p>
<p>使用方法很简单，直接用终端进入到所选定的文件目录，在终端输入：</p>
<p><code>python -m SimpleHTTPServer</code></p>
<p>如果一切正常，会看到如下提示：</p>
<p><code>Serving HTTP on 0.0.0.0 port 8000 ...</code></p>
<p>如果要自定义端口，在命令后面接上端口号即可：</p>
<p><code>python -m SimpleHTTPServer 8080</code></p>
<p>将打开8080端口。</p>
<p>如果所选定的文件目录有index.html，则会展示这个html，否则，则会作为一个文件服务器，展示该文件目录下的所有文件。</p>
<h2 id="用flask框架搭建Web服务器"><a href="#用flask框架搭建Web服务器" class="headerlink" title="用flask框架搭建Web服务器"></a>用flask框架搭建Web服务器</h2><p><strong>flask</strong>框架比较轻便，使用起来很快上手。</p>
<p>同时还要考虑到大量异步访问，可以用<strong>gevent</strong>库，在python3.6上通过验证。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> Flask, request</div><div class="line"><span class="keyword">from</span> gevent <span class="keyword">import</span> monkey</div><div class="line"><span class="keyword">from</span> gevent.pywsgi <span class="keyword">import</span> WSGIServer</div><div class="line"><span class="keyword">import</span> json</div><div class="line"><span class="keyword">import</span> time</div><div class="line"></div><div class="line">monkey.patch_all()</div><div class="line"></div><div class="line">app = Flask(<span class="string">"flaskserver"</span>)</div><div class="line">app.config.update(DEBUG=<span class="keyword">True</span>)</div><div class="line"></div><div class="line"></div><div class="line"><span class="meta">@app.route('/async', methods=['GET'])</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_async_one</span><span class="params">()</span>:</span></div><div class="line">    print(<span class="string">"async has a request"</span>)</div><div class="line">    time.sleep(<span class="number">10</span>)</div><div class="line">    <span class="keyword">return</span> <span class="string">'hello async'</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="meta">@app.route('/hello', methods=['POST'])</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">()</span>:</span></div><div class="line">    paras = request.data</div><div class="line">    j_data = json.loads(paras)</div><div class="line">    print(str(paras))</div><div class="line">    print(str(j_data))</div><div class="line">    <span class="keyword">return</span> <span class="string">'hello test'</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</div><div class="line">    <span class="comment"># app.run(port=8888, debug=True)</span></div><div class="line">    http_server = WSGIServer((<span class="string">''</span>, <span class="number">8888</span>), app)</div><div class="line">    http_server.serve_forever()</div></pre></td></tr></table></figure>
<p>当然，python还有很多web框架可以使用，如Django，Tornado，Web.py等，但基本原理都类似。</p>
<hr>
<p>参考：</p>
<p>[1]. <a href="http://blog.csdn.net/leilba/article/details/50120211" target="_blank" rel="external">python搭建服务器</a></p>
<p>[2]. <a href="http://python.jobbole.com/81524/" target="_blank" rel="external">一起写一个Web服务器</a></p>
<p>[3]. <a href="http://blog.csdn.net/yannanxiu/article/details/52915929" target="_blank" rel="external">Flask实现异步非阻塞请求功能</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/03/16/《心学凶猛》读书笔记/" rel="next" title="《心学凶猛》读书笔记">
                <i class="fa fa-chevron-left"></i> 《心学凶猛》读书笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/05/28/Android之系统时间小结/" rel="prev" title="Android之系统时间小结">
                Android之系统时间小结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/05/27/用Python搭建Web服务器/"
           data-title="用Python搭建Web服务器" data-url="http://martint.oschina.io/2016/05/27/用Python搭建Web服务器/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Martin Tang" />
          <p class="site-author-name" itemprop="name">Martin Tang</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">33</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">8</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#最简单的Web服务器搭建"><span class="nav-number">1.</span> <span class="nav-text">最简单的Web服务器搭建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#用flask框架搭建Web服务器"><span class="nav-number">2.</span> <span class="nav-text">用flask框架搭建Web服务器</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Martin Tang</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"martintang"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  
















  





  

  

  

  

  

  

</body>
</html>
